@page "/connections"
@using BlazorSodDbManager.Models
@using BlazorSodDbManager.Services
@inject ConnectionManager ConnectionManager
@inject NavigationManager NavigationManager
@inject IJSInteropService JSInterop

<h3>Database Connections</h3>

<div class="mb-3">
    <button class="btn btn-primary" @onclick="AddNewConnection">Add New Connection</button>
</div>

@if (_connections.Count == 0)
{
    <div class="alert alert-info">
        No connections found. Click "Add New Connection" to create one.
    </div>
}
else
{
    <div class="table-responsive">
        <table class="table table-striped table-hover">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Type</th>
                    <th>Server</th>
                    <th>Database</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var connection in _connections)
                {
                    <tr>
                        <td>@connection.Name</td>
                        <td>@connection.Type</td>
                        <td>@connection.Server</td>
                        <td>@connection.Database</td>
                        <td>
                            <button class="btn btn-sm btn-primary" @onclick="() => Connect(connection)">Connect</button>
                            <button class="btn btn-sm btn-secondary" @onclick="() => EditConnection(connection)">Edit</button>
                            <button class="btn btn-sm btn-danger" @onclick="() => DeleteConnection(connection)">Delete</button>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
}

@if (_showConnectionDialog)
{
    <div class="modal fade show" style="display: block;" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">@(_isEditing ? "Edit Connection" : "Add New Connection")</h5>
                    <button type="button" class="btn-close" @onclick="CloseDialog"></button>
                </div>
                <div class="modal-body">
                    <EditForm Model="@_currentConnection" OnValidSubmit="SaveConnection">
                        <DataAnnotationsValidator />
                        <ValidationSummary />

                        <div class="mb-3">
                            <label for="name" class="form-label">Connection Name</label>
                            <InputText id="name" @bind-Value="_currentConnection.Name" class="form-control" />
                        </div>

                        <div class="mb-3">
                            <label for="type" class="form-label">Database Type</label>
                            <InputSelect id="type" @bind-Value="_currentConnection.Type" class="form-select">
                                @foreach (var type in Enum.GetValues(typeof(DatabaseType)))
                                {
                                    <option value="@type">@type</option>
                                }
                            </InputSelect>
                        </div>

                        <div class="mb-3">
                            <label for="server" class="form-label">Server</label>
                            <InputText id="server" @bind-Value="_currentConnection.Server" class="form-control" />
                        </div>

                        <div class="mb-3">
                            <label for="port" class="form-label">Port</label>
                            <InputNumber id="port" @bind-Value="_currentConnection.Port" class="form-control" />
                        </div>

                        <div class="mb-3">
                            <label for="database" class="form-label">Database</label>
                            <InputText id="database" @bind-Value="_currentConnection.Database" class="form-control" />
                        </div>

                        <div class="mb-3">
                            <label for="username" class="form-label">Username</label>
                            <InputText id="username" @bind-Value="_currentConnection.Username" class="form-control" />
                        </div>

                        <div class="mb-3">
                            <label for="password" class="form-label">Password</label>
                            <InputText id="password" @bind-Value="_currentConnection.Password" class="form-control" type="password" />
                        </div>

                        <div class="mb-3">
                            <label for="connectionString" class="form-label">Connection String (Optional)</label>
                            <InputTextArea id="connectionString" @bind-Value="_currentConnection.ConnectionString" class="form-control" rows="3" />
                            <small class="form-text text-muted">Leave empty to use the generated connection string based on the fields above.</small>
                        </div>

                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" @onclick="CloseDialog">Cancel</button>
                            <button type="button" class="btn btn-info" @onclick="TestConnection">Test Connection</button>
                            <button type="submit" class="btn btn-primary">Save</button>
                        </div>
                    </EditForm>
                </div>
            </div>
        </div>
    </div>
    <div class="modal-backdrop fade show"></div>
}

@if (_showTestResult)
{
    <div class="modal fade show" style="display: block;" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Connection Test Result</h5>
                    <button type="button" class="btn-close" @onclick="() => _showTestResult = false"></button>
                </div>
                <div class="modal-body">
                    @if (_testSuccess)
                    {
                        <div class="alert alert-success">
                            Connection successful!
                        </div>
                    }
                    else
                    {
                        <div class="alert alert-danger">
                            Connection failed. Please check your connection details.
                        </div>
                    }
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" @onclick="() => _showTestResult = false">Close</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal-backdrop fade show"></div>
}

@code {
    private List<DatabaseConnection> _connections = new List<DatabaseConnection>();
    private DatabaseConnection _currentConnection = new DatabaseConnection();
    private bool _showConnectionDialog = false;
    private bool _isEditing = false;
    private bool _showTestResult = false;
    private bool _testSuccess = false;

    protected override void OnInitialized()
    {
        LoadConnections();
    }

    private void LoadConnections()
    {
        _connections = ConnectionManager.GetConnections();
    }

    private void AddNewConnection()
    {
        _currentConnection = new DatabaseConnection
        {
            Type = DatabaseType.SqlServer,
            Port = 1433
        };
        _isEditing = false;
        _showConnectionDialog = true;
    }

    private void EditConnection(DatabaseConnection connection)
    {
        _currentConnection = new DatabaseConnection
        {
            Id = connection.Id,
            Name = connection.Name,
            Type = connection.Type,
            Server = connection.Server,
            Database = connection.Database,
            Username = connection.Username,
            Password = connection.Password,
            ConnectionString = connection.ConnectionString,
            Port = connection.Port
        };
        _isEditing = true;
        _showConnectionDialog = true;
    }

    private async Task SaveConnection()
    {
        try
        {
            if (_isEditing)
            {
                ConnectionManager.UpdateConnection(_currentConnection);
            }
            else
            {
                await ConnectionManager.AddConnectionAsync(_currentConnection);
            }

            LoadConnections();
            CloseDialog();
        }
        catch (Exception ex)
        {
            // Handle error
            Console.WriteLine(ex.Message);
        }
    }

    private async Task TestConnection()
    {
        _testSuccess = await ConnectionManager.TestConnectionAsync(_currentConnection);
        _showTestResult = true;
    }

    private void DeleteConnection(DatabaseConnection connection)
    {
        ConnectionManager.DeleteConnection(connection.Id);
        LoadConnections();
    }

    private void Connect(DatabaseConnection connection)
    {
        NavigationManager.NavigateTo($"/database/{connection.Id}");
    }

    private void CloseDialog()
    {
        _showConnectionDialog = false;
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JSInterop.InitializeBootstrapComponents();
        }
    }
} 